<template>
  <div class="company-list-page">
    <van-nav-bar title="任务单上报" left-text="返回" left-arrow fixed>
      <template #left>
        <van-icon
          name="arrow-left"
          size="18"
          color="#333"
          @click="$router.go(-1)"
        />
      </template>
      <template #right></template>
    </van-nav-bar>
    <div class="main">
      <canvas ref="pad" />
    </div>
    <div class="corner-actions">
      <van-button
        class="action-btn"
        size="small"
        type="default"
        @click="onCancel"
      >
        <span class="rotate-text">取消</span>
      </van-button>
      <van-button
        class="action-btn"
        size="small"
        type="info"
        @click="onConfirm"
      >
        <span class="rotate-text">确定</span>
      </van-button>
    </div>
    <div class="top-right-tip">
      <span class="rotate-text">请在空白区域内横向书写</span>
    </div>
  </div>
</template>

<script>
import SmoothSignature from "smooth-signature";
import { uploadApi } from "@/api/index";
export default {
  name: "SignaturePage",
  data() {
    return {
      signature: "",
      url: "",
      isUploading: false,
    };
  },
  created() {},
  mounted() {
    this.initCanvas();
    window.addEventListener("resize", this.initCanvas);
  },
  beforeDestroy() {
    window.removeEventListener("resize", this.initCanvas);
  },
  methods: {
    initCanvas() {
      const canvas = this.$refs.pad;
      if (!canvas) return;

      const dpr = window.devicePixelRatio || 1;
      const containerWidth = canvas.parentElement.clientWidth;
      const containerHeight = canvas.parentElement.clientHeight;

      canvas.style.width = containerWidth + "px";
      canvas.style.height = containerHeight + "px";

      canvas.width = Math.floor(containerWidth * dpr);
      canvas.height = Math.floor(containerHeight * dpr);

      this.signature && this.signature.destroy && this.signature.destroy();
      this.signature = new SmoothSignature(canvas, {
        minWidth: 3,
        maxWidth: 8,
        scale: 2,
        color: "#303133",
        bgColor: "#f3f3fa",
      });
    },
    onCancel() {
      // 清空画板
      this.signature.clear();
    },
    dataURLToFile(dataURL, fileName) {
      const arr = dataURL.split(",");
      const mimeMatch = arr[0].match(/:(.*?);/);
      const mime = mimeMatch ? mimeMatch[1] : "image/png";
      const bstr = atob(arr[1]);
      let n = bstr.length;
      const u8arr = new Uint8Array(n);
      while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
      }
      try {
        return new File([u8arr], fileName, { type: mime });
      } catch (e) {
        // 兼容不支持 File 构造器的环境
        return new Blob([u8arr], { type: mime });
      }
    },
    async onConfirm() {
      // 获取签名图片的 dataURL
      this.url = this.signature.getJPG();
      const fileLike = this.dataURLToFile(
        this.url,
        `signature_${Date.now()}.jpg`
      );

      try {
        this.isUploading = true;
        // 若 uploadApi.uploadImage 支持传 File，会在请求层包装为 FormData
        const res = await uploadApi.uploadImage(fileLike);
        if (res && res.errorCode === "000000") {
          // 假设返回的 res.data 为图片 URL
          sessionStorage.setItem("signatureUrl", res.data);
          sessionStorage.setItem("fromSignaturePage", "true");
          this.$router.go(-1);
        }
      } catch (err) {
        console.error("签名上传失败", err);
      } finally {
        this.isUploading = false;
      }
    },
  },
};
</script>

<style lang="less" scoped>
.company-list-page {
  background-color: #fff;
  height: 100vh;
  overflow-y: auto;
  position: relative;
}
.main {
  padding: 46px 0 0;
  height: calc(100vh - 46px);
  /* 兼容 iOS 安全区域，避免底部空白 */
  padding-bottom: constant(safe-area-inset-bottom);
  padding-bottom: env(safe-area-inset-bottom);
}
.corner-actions {
  position: fixed;
  left: 12px;
  bottom: 12px;
  display: flex;
  flex-direction: column;
  gap: 12px;
  z-index: 10;
}
.corner-actions .van-button {
  display: block;
  line-height: 1;
  padding: 10px 8px;
  width: 44px; /* 视觉上接近截图宽度 */
  height: 92px; /* 视觉上接近截图高度 */
  border-radius: 8px;
  justify-content: center;
  align-items: center;
}
.rotate-text {
  display: inline-block;
  transform: rotate(90deg);
  transform-origin: center;
}
.top-right-tip {
  position: fixed;
  right: 30px; /* 与右边框基准间距 */
  top: 220px;
  color: rgba(0, 0, 0, 0.45);
  font-size: 12px;
  z-index: 10;
}
/* 仅针对右上角提示，使用右上角为旋转锚点并做位移补偿，避免旋转导致偏移 */
.top-right-tip .rotate-text {
  transform-origin: top right;
  transform: rotate(90deg) translateY(-100%);
  white-space: nowrap;
}
/* 消除 canvas 行内元素基线缝隙 */
canvas {
  display: block;
}
</style>
